package com.example.DataSource.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.DataSource.Service.psychoService;
import com.example.DataSource.entity.member;
import com.example.DataSource.entity.psycho_ask;
import com.example.DataSource.Mapper.psychoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class psychoServiceImpl extends ServiceImpl<psychoMapper, psycho_ask> implements psychoService {

    @Override
    @Transactional // 使用事务注解，确保查询过程的事务性
    public IPage<psycho_ask> getPsychoAskPage(Page<psycho_ask> page) {
        // 使用 MyBatis-Plus 的分页查询方法，查询未删除的记录
        IPage<psycho_ask> psychoPage = this.page(page, new QueryWrapper<psycho_ask>());
//        IPage<psycho_ask> psychoPage = this.page(page, new QueryWrapper<psycho_ask>().eq("is_delete", "0"));

        // 获取查询结果的记录列表
        List<psycho_ask> records = psychoPage.getRecords();
        // 遍历记录列表，为每个记录设置 member_name
        for (psycho_ask ask : records) {
            // 调用 getMemberName 方法获取 member_name
            String memberName = getMemberName(ask.getMember_id());
            // 将获取到的 member_name 设置到记录中
            ask.setMember_name(memberName);
        }
        // 返回包含 member_name 的分页结果
        return psychoPage;
    }

    @Autowired
    private memberServiceImpl memberService;
    private String getMemberName(int memberId) {
        QueryWrapper<member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("id",memberId);
        List<member> list = memberService.list(memberQueryWrapper);
        return list.get(0).getUsername();
    }

    @Transactional // 使用事务注解，确保查询过程的事务性
    public IPage<psycho_ask> getPsychoAskPageSearch(Page<psycho_ask> page, String searchInfo) {
        // 使用 MyBatis-Plus 的分页查询方法，查询未删除的记录
        QueryWrapper<psycho_ask> queryWrapper =  new QueryWrapper<>();
        queryWrapper
                .like("title",searchInfo)
                .or()
                .like("intro",searchInfo);
        IPage<psycho_ask> psychoPage = this.page(page, queryWrapper);
        // 获取查询结果的记录列表
        List<psycho_ask> records = psychoPage.getRecords();
        // 遍历记录列表，为每个记录设置 member_name
        for (psycho_ask ask : records) {
            // 调用 getMemberName 方法获取 member_name
            String memberName = getMemberName(ask.getMember_id());
            // 将获取到的 member_name 设置到记录中
            ask.setMember_name(memberName);
        }
        // 返回包含 member_name 的分页结果
        return psychoPage;
    }
}
